package com.meihua.baoleyi.net;

import android.text.TextUtils;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.meihua.baoleyi.base.BaseResponse;
import com.meihua.baoleyi.common.MyApp;
import com.meihua.baoleyi.utils.MD5;

import java.util.Iterator;
import java.util.Set;
import java.util.TreeMap;

/**
 * Created by ${zhangyuanchao} on 2017/10/26.
 */

public class NetHelper {
    /*post 请求*/
    public static void post(String url, TreeMap<String, String> params, boolean isDecode,HttpCallBack callBack) {
        if (TextUtils.isEmpty(url)) {
            throw new IllegalArgumentException("params is null");
        }
        TreeMap<String, String> decode = params;
        /*加密*/
        if (isDecode) {
            decode = decode(params);
        }
        OkGo.<String>post(url).params(decode).execute(callBack);
    }

    /*post 请求*/
    public static void get(String url, TreeMap<String, String> params, boolean isDecode,HttpCallBack callBack) {
        if (TextUtils.isEmpty(url)) {
            throw new IllegalArgumentException("params is null");
        }
        TreeMap<String, String> decode = params;
        /*加密*/
        if (isDecode) {
            decode = decode(params);
        }
        OkGo.<String>get(url).params(decode).execute(callBack);
    }

    /**
     * 加密
     *
     * @param params
     * @return
     */
    public static TreeMap<String, String> decode(TreeMap<String, String> params) {
        TreeMap<String, String> temp = params;
        String time = (System.currentTimeMillis() + "").substring(0, 10);
        String token = MyApp.getInstance().getToken().toString();
        temp.put("token", token);
        temp.put("timestamp", time);
        Set<String> keySet = temp.keySet();
        Iterator<String> iterator = keySet.iterator();
        StringBuilder sb = new StringBuilder();
        while (iterator.hasNext()) {
            String key = iterator.next();
            String value = temp.get(key);
            sb.append(key + "=" + value + "&");
        }
        String sin1 = sb.substring(0, sb.length()-1);
        String sign_yes = MD5.encode(sin1.toString()).toUpperCase();
        temp.put("sign", sign_yes);
        return temp;
    }

    /*回调*/
    public static abstract class HttpCallBack extends StringCallback {

    }

    public static <T> T getBeanForJson(Class clazz, String json) {
        try {
            T t = (T) new Gson().fromJson(json, clazz);
            return t;
        } catch (Exception e) {
            try {
                BaseResponse b = new Gson().fromJson(json, BaseResponse.class);
                Toast.makeText(MyApp.getContext(),"数据格式错误",Toast.LENGTH_SHORT).show();
                return null;
            } catch (Exception e1) {
                e1.printStackTrace();
                return null;
            }
        }
    }
}
